/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ProgPanel.java
 *
 * Created on 05/12/2011, 04:17:48
 */
package proj5labbd.graphics.consultas;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

/*
 * Painel  para a seleção pré definida pelos desenvolvedores
 * Consulta exibe os episodios com a média de ibope maior que 20
 */
public class SeriePanel extends OperationPanel {

    /** Creates new form ProgPanel */
    public SeriePanel(SerieFrame frame, DBInterface dbInterface) {
        super(frame,dbInterface);
        try {
            initComponents();
            jbtOk.addActionListener(new SerieAction());
            Statement stmt = dbInterface.getConn().createStatement();
            stmt.executeQuery(query);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível gerar o relatório.");
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
   
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jlbpt1 = new javax.swing.JLabel();
        jlbpt2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbSerie = new javax.swing.JTable();
        jbtOk = new javax.swing.JButton();

        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jlbpt1.setText("Média de ibope e ibope máximo,");

        jlbpt2.setText("para séries com ibope médio maior que 20");

        jtbSerie.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jtbSerie);

        jbtOk.setText("Ok");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jlbpt2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jlbpt1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(101, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jbtOk, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jlbpt1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jlbpt2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 218, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtOk))
        );
    }// </editor-fold>//GEN-END:initComponents

    //ação ocasionada pela apresentação do Painel ao usuário
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        // TODO add your handling code here:
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
            frame.printException(ex);
            JOptionPane.showMessageDialog(null, "Não foi possível resgatar os dados da tabela.");
        }
    }//GEN-LAST:event_formComponentShown

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtOk;
    private javax.swing.JLabel jlbpt1;
    private javax.swing.JLabel jlbpt2;
    private javax.swing.JTable jtbSerie;
    // End of variables declaration//GEN-END:variables

    //configura a(s) tabela(s) de acordo com dados resgatados na base de dados
     private void setupTable() throws SQLException {
            
         Statement stmt = dbInterface.getConn().createStatement();
         ResultSet rs = stmt.executeQuery("SELECT * FROM ib");
         
         String [][] sArray = dbInterface.rsToStringArray(rs);

        DefaultTableModel model = new DefaultTableModel(sArray,
                new String[]{"Série","Ibope Médio","Ibope Máximo"}
                );
        jtbSerie.setModel(model);
         
         
    }
    
     //ação do botão Ok
    class SerieAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {

            if (e.getSource() == jbtOk) {
                frame.dispose();
                
            }

        }


    }
    
    //Script SQL da busca pré-definida
    private final String query = "CREATE OR REPLACE VIEW ib AS "+
                                     "SELECT serie.tituloPr AS Serie, AVG(exibicaoSerie.ibopeExSe) AS Ibope_Medio, MAX(exibicaoSerie.ibopeExSe) AS Ibope_Máximo "+
                                     "FROM serie JOIN temporada JOIN episodioSerie JOIN exibicaoSerie " +
                                     "ON (episodioSerie.idPr = exibicaoSerie.idPr AND episodioSerie.nroTe = exibicaoSerie.nroTe AND episodioSerie.nroEpSe = exibicaoSerie.nroEpSe) "+
                                     "ON (temporada.idPr = episodioSerie.idPr AND temporada.nroTe = episodioSerie.nroTe) "+
                                     "ON serie.idPr = temporada.idPr "+
                                     "GROUP BY serie.tituloPr "+
                                     "HAVING AVG(exibicaoSerie.ibopeExSe) > 20.0 ";
                                  

}
